<template>
  <BasicForm @register="registerForm" v-loading="loading" >
  
    <template #footer-action="{ model, field }">
      <a-button class="mr-2">查看</a-button>
      <a-button type="primary" class="mr-2" @click="handleSubmit"  v-if="!isSetting">生成</a-button>
      <a-button type="primary" @click="handleSubmit" v-else>变更</a-button>
    </template>
  </BasicForm>
</template>
<script lang="ts" setup name="AppConfig">
  import { ref, computed, unref, nextTick, onMounted, watch } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { secretFormSchema } from "../data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { isEmpty } from "/@/utils";
  import { VerifyModal } from "/@/components/BizVerify"
  import * as appApi from "/@/api/iam/app"
  import * as fileApi from "/@/api/infra/file"
  const { createMessage, createConfirm } = useMessage()

  const emit = defineEmits(["success", "register"])
  const isSetting = ref(false)
  const rowId = ref("")
  const loading = ref(false)
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: secretFormSchema,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, sm: 24 },
  })

  const props = defineProps({
    data: { type: Object }
  })

  onMounted(() => {
    // fileApi.getUploadToken({ fileName: 'test.png', fileSize: 1000, bizType: 'avatar' })
  })

  
  watch(
    () => props.data,
    (data) => {
      nextTick(() => {
        initData(data)
      })
      
    }, 
    { immediate: true }
  )

  const initData = async (data) => {
    if (!data) {
      return
    }
    isSetting.value = data?.publicKey != undefined
    await resetFields()
    rowId.value = data.id
    setFieldsValue({ ...data, loginRedirectUrls: JSON.stringify(data.loginRedirectUrls) })
  }

  async function handleSubmit() {
    try {
      let values = await validate()
      console.log("submit", values)
      const loginRedirectUrls = JSON.parse(values.loginRedirectUrls).filter(e => !isEmpty(e))
      if (loginRedirectUrls.length == 0) {
        createMessage.error('登录成功回调url不能为空')
        return
      }
      values.loginRedirectUrls = loginRedirectUrls
      loading.value = true
      await appApi.updateApp(values)
      emit("success", { ...values})
      createMessage.success('保存成功')
    } finally {
      loading.value = false
    }
  }
</script>
